<template>
	<div class="pipeline-execution">
		<el-form
			:model="queryParams"
			ref="queryForm"
			size="small"
			:inline="true"
			label-width="85px"
		>
			<el-form-item
				label="部署id"
				prop="code"
			>
				<el-input
					v-model="queryParams.id"
					style="width: 240px"
					placeholder="请输入部署id"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item
				label="部署类型"
				prop="deployType"
			>
				<el-select
					v-model="queryParams.deployType"
					placeholder="请选择部署类型"
					style="width: 240px"
				>
					<el-option
						v-for="item in deployTypeOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item
				label="部署描述"
				prop="code"
			>
				<el-input
					v-model="queryParams.info"
					style="width: 240px"
					placeholder="请输入部署描述"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item
				label="创建时间"
				prop="createTime"
			>
				<el-date-picker
					v-model="queryParams.createTime"
					style="width: 240px"
					value-format="yyyy-MM-dd HH:mm:ss"
					type="daterange"
					range-separator="-"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					:default-time="['00:00:00', '23:59:59']"
				/>
			</el-form-item>
			<el-form-item
				label="关键字查询"
				prop="code"
			>
				<el-input
					v-model="queryParams.data"
					style="width: 240px"
					placeholder="请输入tag/服务services"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					icon="el-icon-search"
					@click="handleQuery"
					>搜索</el-button
				>
				<el-button
					icon="el-icon-refresh"
					@click="resetQuery"
					>重置</el-button
				>
			</el-form-item>
		</el-form>
		<!-- v-hasPermi="[]" -->
		<el-row>
			<el-col>
				<el-button
					class="pipeline-execution-add"
					type="primary"
					@click="deployHandle"
					>新增部署</el-button
				>
			</el-col>
		</el-row>
		<el-table
			v-loading="loading"
			:data="list"
		>
			<el-table-column
				prop="id"
				align="center"
				label="部署id"
				width="90"
			/>
			<el-table-column
				prop="deployType"
				label="部署类型"
				align="center"
				show-overflow-tooltip
				width="130"
			>
				<template #default="{ row }">
					{{ deployTypeOptions?.filter(item => item.value === row.deployType)?.[0]?.label ?? '-' }}
				</template>
			</el-table-column>
			<el-table-column
				prop="info"
				label="部署描述"
				align="center"
				show-overflow-tooltip
			/>

			<!-- Tags 列 -->
			<el-table-column
				label="tag"
				align="center"
				width="145"
			>
				<template #default="{ row }">
					<div
						v-for="(tagItem, index) in row.tags"
						:key="index"
						class="tags-tag"
					>
						<el-tag style="margin-right: 5px; margin-bottom: 5px">
							{{ tagItem.tag }}
						</el-tag>
					</div>
				</template>
			</el-table-column>

			<!-- Services 列 -->
			<el-table-column
				label="服务"
				width="120"
				align="center"
			>
				<template #default="{ row }">
					<div class="column-services">
						<el-popover
							v-for="(tagItem, tagIndex) in row.tags"
							placement="right"
							title="服务列表"
							trigger="hover"
							:key="tagIndex"
						>
							<div
								class="popover-reference"
								slot="reference"
							>
								查看服务器
							</div>
							<div class="column-services-item">
								<div
									v-for="(service, serviceIndex) in tagItem.services"
									:key="serviceIndex"
								>
									<el-tag style="margin-right: 5px; margin-bottom: 5px">
										{{ service.name }}
									</el-tag>
								</div>
							</div>
						</el-popover>
					</div>
				</template>
			</el-table-column>

			<el-table-column
				label="环境"
				width="180"
				prop="env"
				align="center"
			>
				<template #default="{ row }">
					<el-select
						v-model="envSelectValues[row.id]"
						multiple
						collapse-tags
						style="margin-left: 20px"
						placeholder="请选择"
						class="env-select"
					>
						<el-option
							v-for="item in envOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</template>
			</el-table-column>
			<el-table-column
				label="创建时间"
				width="180"
				prop="createTime"
				align="center"
			>
				<template v-slot="scope">
					<span>{{ parseTime(scope.row.createTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column
				label="操作"
				align="center"
				width="245"
				class-name="small-padding fixed-width"
				fixed="right"
			>
				<template v-slot="scope">
					<el-button
						v-for="item in optButtonList"
						size="mini"
						type="text"
						:key="item.key"
						:icon="item.icon"
						@click="item.onClick(scope.row)"
						v-text="item.label"
					/>
					<!-- v-hasPermi="item.hasPermi" -->
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			:page.sync="queryParams.pageNo"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>
		<DeployDialog
			v-if="dialogVisible"
			:deployTypeOptions="deployTypeOptions"
			:dialogType="dialogType"
			:id="dialogId"
			:respData="respData"
			@dialogHandle="dialogHandle"
		/>
	</div>
</template>

<script>
import DeployDialog from './components/deployDialog.vue';
import {
	piplineDeployPage,
	piplineExecCreate,
	piplineDeployCreate,
	piplineDeployUpdata,
	piplineDeleteModel,
	systemDictDataType,
} from '@/api/pipeline/pipeline-execution';

export default {
	name: 'pipelineExecution',
	components: {
		DeployDialog,
	},
	data() {
		return {
			dialogVisible: false,
			dialogType: 'add',
			dialogId: '',
			respData: {},
			envSelectValues: {},
			deployTypeOptions: [],
			optButtonList: [
				{
					label: '删除部署',
					key: 'delete',
					icon: 'el-icon-delete',
					onClick: row => this.buttonHandle('delete', row),
					hasPermi: [''],
				},
				{
					label: '执行部署',
					key: 'execution',
					icon: 'el-icon-switch-button',
					onClick: row => this.buttonHandle('execution', row),
					hasPermi: [''],
				},
				{
					label: '执行状态',
					key: 'executionStatus',
					icon: 'el-icon-view',
					onClick: row => this.buttonHandle('executionStatus', row),
					hasPermi: [''],
				},
			],
			envOptions: [],
			// 遮罩层
			loading: true,
			// 导出遮罩层
			exportLoading: false,
			// 总条数
			total: 0,
			// 部署列表
			list: [],
			// 查询参数
			queryParams: {
				pageNo: 1,
				pageSize: 10,
				id: undefined,
				info: undefined,
				data: undefined,
				deployType: undefined,
				createTime: [],
			},
			task: false,
		};
	},
	async created() {
		this.getList();
		try {
			const { data } = await systemDictDataType({ type: 'env2' });
			this.envOptions = data;
		} catch (error) {
			this.$message.error(error);
		}
		try {
			const { data } = await systemDictDataType({ type: 'deploy_type' });
			this.deployTypeOptions = data;
		} catch (error) {
			this.$message.error(error);
		}
	},
	methods: {
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNo = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.queryParams = {
				pageNo: 1,
				pageSize: 10,
				id: undefined,
				info: undefined,
				tag: undefined,
				createTime: [],
			};
			this.handleQuery();
		},
		async dialogHandle(type, modelForm) {
			switch (type) {
				case 'cancel':
					this.getList();
					this.dialogVisible = false;
					this.dialogId = '';
					this.respData = {};
					break;
				case 'confirm':
					{
						try {
							const api = {
								add: piplineDeployCreate,
								edit: piplineDeployUpdata,
							}[this.dialogType];
							const obj = {
								...modelForm,
								env: '2',
							};

							await api(obj);
							this.dialogHandle('cancel');
							this.$message.success('操作成功');
						} catch (error) {
							this.$message.error(error);
						}
					}
					break;
			}
		},
		async deployHandle() {
			this.dialogType = 'add';
			this.dialogVisible = true;
		},
		/** 查询列表 */
		async getList() {
			try {
				this.loading = true;
				const res = await piplineDeployPage({
					...this.queryParams,
					env: '2',
				});
				this.list = res.data.list ?? [];
				this.total = res.data.total;
				this.list.forEach(item => {
					if (!Object.prototype.hasOwnProperty.call(this.envSelectValues, item.id)) {
						this.envSelectValues = Object.assign({}, this.envSelectValues, {
							[item.id]: [],
						});
					}
				});
			} finally {
				this.loading = false;
				this.task = false;
			}
		},
		async buttonHandle(type, row) {
			try {
				switch (type) {
					case 'delete':
						this.getAlert('删除部署', '是否要删除部署？', async action => {
							if (action === 'confirm') {
								if (this.task) return;
								this.task = true;
								await piplineDeleteModel(row.id);
								this.getList();
								this.$message.success('操作成功');
							}
						});
						break;
					case 'execution':
						if (this.envSelectValues[row.id]?.length > 0) {
							this.getAlert('执行部署', '是否要执行部署？', async action => {
								if (action === 'confirm') {
									if (this.task) return;
									this.loading = true;
									this.task = true;
									await piplineExecCreate({
										deployId: row.id,
										envs: this.envSelectValues[row.id],
										deployType: row.deployType,
									});
									this.envSelectValues = {};
									this.getList();
									this.$message.success('操作成功');
								}
							});
						} else {
							this.$message.error('请选择部署环境');
						}
						break;
					case 'executionStatus':
						this.$router.push({
							path: '/pipeline/prd-execution/detail',
							query: {
								id: row.id,
								option: JSON.stringify(this.deployTypeOptions),
							},
						});
						break;
				}
			} catch (err) {
				this.$message.error(err);
				this.task = false;
				this.loading = false;
			}
		},
		getAlert(title, content, callback) {
			this.$alert(content, title, {
				distinguishCancelAndClose: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				showCancelButton: true,
				callback,
			});
		},
	},
};
</script>

<style lang="scss" scoped>
.pipeline-execution {
	padding: 16px 10px;

	&-add {
		margin-bottom: 16px;
		height: 32px;
		line-height: 32px;
		padding: 0 12px;
	}
}

.env-select,
:deep(.el-input__inner) {
	height: 32px;
}

.column-services {
	text-align: center;

	.popover-reference {
		cursor: pointer;
		margin: 0 auto 5px;
		width: 80px;
		height: 28px;
		line-height: 28px;
		text-align: center;
		color: #1890ff;

		&:hover {
			opacity: 0.8;
		}
	}
	&-item {
		max-height: 300px;
		overflow-y: auto;
	}
}
</style>
